package com.lifeverse.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;

import java.util.Set;

/**
 * 角色实体
 */
@Entity
@Table(name = "roles", indexes = {
    @Index(name = "idx_role_code", columnList = "role_code", unique = true),
    @Index(name = "idx_role_name", columnList = "role_name")
})
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Role extends BaseEntity {
    
    /**
     * 角色代码
     */
    @Column(name = "role_code", nullable = false, unique = true, length = 50)
    private String roleCode;
    
    /**
     * 角色名称
     */
    @Column(name = "role_name", nullable = false, length = 100)
    private String roleName;
    
    /**
     * 角色描述
     */
    @Column(name = "description", length = 500)
    private String description;
    
    /**
     * 是否启用
     */
    @Column(name = "enabled", nullable = false)
    private Boolean enabled;
    
    /**
     * 是否为系统角色
     */
    @Column(name = "is_system", nullable = false)
    private Boolean isSystem;
    
    /**
     * 排序号
     */
    @Column(name = "sort_order")
    private Integer sortOrder;
    
    /**
     * 角色权限
     */
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "role_permissions",
        joinColumns = @JoinColumn(name = "role_id"),
        inverseJoinColumns = @JoinColumn(name = "permission_id")
    )
    private Set<Permission> permissions;
    
    /**
     * 创建角色的静态方法
     */
    public static Role create(String roleCode, String roleName, String description) {
        return Role.builder()
                .roleCode(roleCode)
                .roleName(roleName)
                .description(description)
                .enabled(true)
                .isSystem(false)
                .sortOrder(0)
                .build();
    }
    
    /**
     * 创建系统角色的静态方法
     */
    public static Role createSystemRole(String roleCode, String roleName, String description) {
        return Role.builder()
                .roleCode(roleCode)
                .roleName(roleName)
                .description(description)
                .enabled(true)
                .isSystem(true)
                .sortOrder(0)
                .build();
    }
    
    /**
     * 检查角色是否有指定权限
     */
    public boolean hasPermission(String permissionCode) {
        return permissions.stream()
                .anyMatch(permission -> permission.getPermissionCode().equals(permissionCode));
    }
}